package band.wukong.practice.javase.core.net.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Johnson
 * Date: 2012-8-24 21:19:08
 * To change this template use File | Settings | File Templates.
 */
public class ChatServer {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws Exception {
        List sockets = new ArrayList();
        ServerSocket ss = new ServerSocket(9000);
        while (true) {
            Socket s = ss.accept();
            sockets.add(s);
            Thread t = new ServerThread(s, sockets);
            t.start();
        }
    }
}

class ServerThread extends Thread {
    private Socket s;
    private List sockets;

    public ServerThread(Socket s, List sockets) {
        super();
        this.s = s;
        this.sockets = sockets;
    }

    public void run() {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            while (true) {
                String text = in.readLine();
                if (text == null) break;
                Iterator it = sockets.iterator();
                while (it.hasNext()) {
                    Socket s2 = (Socket) it.next();
                    PrintWriter out = new PrintWriter(s2.getOutputStream());
                    out.println(text);
                    out.flush();
                }
            }
        } catch (IOException e) {

        }
        finally {
            sockets.remove(s);
            try {
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
